import {
  Tree,
  DataSet,
} from 'choerodon-ui/pro';
import Record from 'choerodon-ui/pro/lib/data-set/Record';
import React, { useMemo } from 'react';
import axios from 'axios';
import {EventDataNode} from 'choerodon-ui/lib/tree';
import treeDS from './treeDataSet';

interface NodeProps {
  title: string,
  isLeaf?: boolean,
}
interface Item {
  parentId:string,
  id:string,
}

// 这里面可以控制node结点的判断来实现是否展示为叶结点
function nodeCover({ record }: { record?: Record | null | undefined }): NodeProps {
  console.log(record);
  const nodeProps: NodeProps = {
    title: record?.get('text'),
  };
  if (record?.get('text') === '岗位管理') {
    nodeProps.isLeaf = true;
  }
  return nodeProps;
}

const TreeAsync = () => {
  const treeDataSet = useMemo(() => new DataSet(treeDS()), []);
  const onLoadData = (event: EventDataNode):Promise<void> => {
    // @ts-ignore
    const {key, children} = event;
    return new Promise(resolve => {
      if (!children) {
        axios.post('/_api/tree/async').then((res) => {
          const remianData = treeDataSet.toData();
          // 获取子结点数据，绑定父节点
          // @ts-ignore
          const recordsChildren:Item[] = res.content.map((item:Item) => {
            const copyItem = item;
            copyItem.parentId = key.toString();
            copyItem.id = (Math.random() * 100).toString();
            return item;
          });
          // 生成完成的dataSet数据注意会触发load event
          treeDataSet.loadData([...remianData, ...recordsChildren]);
          resolve();
        }).catch(() => {
          resolve();
        });
      } else {
        resolve();
      }
    });
  };

  return (
    <Tree
      dataSet={treeDataSet}
      loadData={onLoadData}
      checkable
      treeNodeRenderer={nodeCover}
    />
  );
};

export default TreeAsync;